package com.njtoyo.taxi.admin.rest.controller.business.operation_rule;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author mdf
 * @title: Demo
 * @description: TODO
 * @date 2025/2/13 16:16
 */
public class Demo {

    public static void main(String[] args) {
        List<TimeInterval> timeIntervals = new ArrayList<>();

        timeIntervals.add(new TimeInterval("00:00", "23:59"));

        boolean isValid = checkTimeIntervals(timeIntervals);
        System.out.println("时间区间是否有效: " + isValid);
    }

    public static boolean checkTimeIntervals(List<TimeInterval> timeIntervals) {
        // 按开始时间排序
        Collections.sort(timeIntervals, Comparator.comparing(TimeInterval::getStartTime));

        // 检查是否从 00:00 开始
        if (timeIntervals.isEmpty() || !timeIntervals.get(0).getStartTime().equals(LocalTime.MIN)) {
            return false;
        }

        LocalTime previousEndTime = LocalTime.MIN;
        for (TimeInterval interval : timeIntervals) {
            // 检查结束时间是否大于开始时间
            if (!interval.getEndTime().isAfter(interval.getStartTime())) {
                return false;
            }

            // 检查是否有交集
            if (interval.getStartTime().isBefore(previousEndTime)) {
                return false;
            }

            // 检查是否连续
            if (!interval.getStartTime().equals(previousEndTime)) {
                return false;
            }

            // 更新上一个结束时间
            previousEndTime = interval.getEndTime();
        }

        // 检查是否覆盖到 23:59
        return previousEndTime.format(DateTimeFormatter.ofPattern("HH:mm")).equals("23:59");
    }

    static class TimeInterval {
        private final LocalTime startTime;
        private final LocalTime endTime;

        public TimeInterval(String startTime, String endTime) {
            this.startTime = LocalTime.parse(startTime);
            this.endTime = LocalTime.parse(endTime);
        }

        public LocalTime getStartTime() {
            return startTime;
        }

        public LocalTime getEndTime() {
            return endTime;
        }
    }
}
